﻿using Common.Common;
using DataCenter;
using DBLibrary;
using DcpServer.Common;
using DcpServer.Domain;
using DcpServer.Model.Enum;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TouchSocket.Core;
using TouchSocket.Http;
using TouchSocket.Rpc;
using TouchSocket.Rpc.WebApi;
using TouchSocket.Sockets;
using WSDTO;

namespace WSLibrary
{
    public class ApiServer : RpcServer
    {

        // Server 启动
        public static void InitApiServer()
        {
            HttpService service = new HttpService();
            service.Setup(new TouchSocketConfig()
               .UsePlugin()
               .SetListenIPHosts(new IPHost[] { new IPHost(7789) })
               .ConfigureContainer(a =>
               {
                   a.SetSingletonLogger<ConsoleLogger>();//注册一个日志
               })
               .ConfigureRpcStore(a =>
               {
                   a.RegisterServer<ApiServer>();//注册服务
               })
               .ConfigurePlugins(a =>
               {
                   a.UseCheckClear();
                   a.UseWebApi();//启用WebApi
               }))
               .Start();

            LogHelper.Info("WebApiServer 已经启动");
        }


        [Origin(AllowOrigin = "*")]//跨域设置
        [Router("/activeDevices")]
        [WebApi(HttpMethodType.GET)]
        public string ActiveDevices()
        {
            try
            {
                List<DeviceDTO> deviceDTOs = new List<DeviceDTO>();
                foreach (string key in WebContext.OnlinePatient.Keys)
                {
                    Patient patient = WebContext.OnlinePatient[key];
                    PatientRepository patientRepository = new PatientRepository();
                    //NibpReview lastNibpReview = patientRepository.getLastNibpReview(patient.Id);
                    DeviceDTO deviceDTO = new DeviceDTO()
                    {
                        age = patient.Age,
                        bedId = patient.HospitalBedNo,
                        //createTime = patient.CreateTime.ConvertTime(),
                        createTime = CommonHelper.GetTimeStamp(patient.CreateTime),
                        deviceId = key,
                        gender = patient.Sex == EnumSex.Male ? 1 : 2,
                        patientId = patient.Id.ToString(),
                        patientName = patient.PatientName,
                        //lastNibpReview = lastNibpReview

                    };
                    deviceDTOs.Add(deviceDTO);

                }
                string result = JsonConvert.SerializeObject(deviceDTOs);
                return result;
            }catch(Exception e)
            {
                LogHelper.Error(e.Message);
                return null;
            }
            
        }


        [Origin(AllowOrigin = "*")]//跨域设置
        [Router("/history/hr")]
        [WebApi(HttpMethodType.GET)]
        public string HrHistory(string deviceId, string interval)
        {
            Patient patient = WebContext.OnlinePatient[deviceId];
            if (patient == null)
            {
                return null;
            }
            PatientRepository patientRepository = new PatientRepository();
            MainDataTable dataTable = patientRepository.GetMainDataTables(patient.Id, 0);
            byte[] hr = new byte[dataTable.Hr.Length/60];
            for(int i = 0;  i< hr.Length; i++)
            {
                hr[i] = dataTable.Hr[60 * i];
            }
            int num = Convert.ToInt32(interval) * 60;
            // 如果数据不满interval，全部显示
            List<int> hrList = new List<int>();
            if (num >= hr.Length)
            {
                foreach (var heart in hr)
                {
                    hrList.Add((Convert.ToInt32(heart)));
                }

                TimeValueWithFirstTimeDTO timeValueWithFirstTimeDTO = new TimeValueWithFirstTimeDTO()
                {
                    firstTime = CommonHelper.GetTimeStamp(dataTable.StartTime),
                    pointInterval = num / 60,
                    values = hrList,
                };
                return JsonConvert.SerializeObject(timeValueWithFirstTimeDTO);
            }// 数据够了从List之中截取
            else
            {

                int start = hr.Length - num;
                for (int i = start; i < hr.Length; i++)
                {
                    hrList.Add((Convert.ToInt32(hr[i])));
                }
                TimeValueWithFirstTimeDTO timeValueWithFirstTimeDTO = new TimeValueWithFirstTimeDTO()
                {
                    firstTime = CommonHelper.GetTimeStamp(dataTable.StartTime.AddMinutes(start + 1)),
                    pointInterval = num / 60,
                    values = hrList
                };
                return JsonConvert.SerializeObject(timeValueWithFirstTimeDTO);

            }
        }


        [Origin(AllowOrigin = "*")]//跨域设置
        [Router("/history/spo2")]
        [WebApi(HttpMethodType.GET)]
        public string Spo2History(string deviceId, string interval)
        {
            Patient patient = WebContext.OnlinePatient[deviceId];
            if (patient == null)
            {
                return null;
            }
            PatientRepository patientRepository = new PatientRepository();
            MainDataTable dataTable = patientRepository.GetMainDataTables(patient.Id, 0);
            byte[] spo2 = new byte[dataTable.Spo2.Length / 60];
            for (int i = 0; i < spo2.Length; i++)
            {
                spo2[i] = dataTable.Spo2[60 * i];
            }

            int num = Convert.ToInt32(interval) * 60;
            // 如果数据不满interval，全部显示
            List<int> spo2List = new List<int>();
            if (num >= spo2.Length)
            {
                foreach (var ir in spo2)
                {
                    spo2List.Add((Convert.ToInt32(ir)));
                }

                TimeValueWithFirstTimeDTO timeValueWithFirstTimeDTO = new TimeValueWithFirstTimeDTO()
                {
                    firstTime = CommonHelper.GetTimeStamp(dataTable.StartTime),
                    pointInterval = num / 60,
                    values = spo2List,
                };
                return JsonConvert.SerializeObject(timeValueWithFirstTimeDTO);
            }// 数据够了从List之中截取
            else
            {

                int start = spo2.Length - num;
                for (int i = start; i < spo2.Length; i++)
                {
                    spo2List.Add((Convert.ToInt32(spo2[i])));
                }
                TimeValueWithFirstTimeDTO timeValueWithFirstTimeDTO = new TimeValueWithFirstTimeDTO()
                {
                    firstTime = CommonHelper.GetTimeStamp(dataTable.StartTime.AddMinutes(start + 1)),
                    pointInterval = num / 60,
                    values = spo2List
                };
                return JsonConvert.SerializeObject(timeValueWithFirstTimeDTO);

            }
        }


        [Origin(AllowOrigin = "*")]//跨域设置
        [Router("/history/resp")]
        [WebApi(HttpMethodType.GET)]
        public string RespHistory(string deviceId, string interval)
        {
            Patient patient = WebContext.OnlinePatient[deviceId];
            if (patient == null)
            {
                return null;
            }
            PatientRepository patientRepository = new PatientRepository();
            MainDataTable dataTable = patientRepository.GetMainDataTables(patient.Id, 0);
            byte[] Resp = new byte[dataTable.Resp.Length / 60];
            for (int i = 0; i < Resp.Length; i++)
            {
                Resp[i] = dataTable.Resp[60 * i];
            }
            int num = Convert.ToInt32(interval) * 60;
            // 如果数据不满interval，全部显示
            List<int> respList = new List<int>();
            if (num >= Resp.Length)
            {
                foreach (var resp in Resp)
                {
                    respList.Add((Convert.ToInt32(resp)));
                }

                TimeValueWithFirstTimeDTO timeValueWithFirstTimeDTO = new TimeValueWithFirstTimeDTO()
                {
                    firstTime = CommonHelper.GetTimeStamp(dataTable.StartTime),
                    pointInterval = num / 60,
                    values = respList
                };
                return JsonConvert.SerializeObject(timeValueWithFirstTimeDTO);
            }// 数据够了从List之中截取
            else
            {

                int start = Resp.Length - num;
                for (int i = start; i < Resp.Length; i++)
                {
                    respList.Add((Convert.ToInt32(Resp[i])));
                }
                TimeValueWithFirstTimeDTO timeValueWithFirstTimeDTO = new TimeValueWithFirstTimeDTO()
                {
                    firstTime = CommonHelper.GetTimeStamp(dataTable.StartTime.AddMinutes(start + 1)),
                    pointInterval = num / 60,
                    values = respList
                };
                return JsonConvert.SerializeObject(timeValueWithFirstTimeDTO);

            }
        }


        [Origin(AllowOrigin = "*")]//跨域设置
        [Router("/history/nibp")]
        [WebApi(HttpMethodType.GET)]
        public string NibpHistory(string deviceId)
        {
            Patient patient = WebContext.OnlinePatient[deviceId];
            if (patient == null)
            {
                return null;
            }
            
            PatientRepository repository = new PatientRepository();
            List<NIBPDTO> nIBPDTOs = repository.GetNibpReviews(patient.Id);
           
            return JsonConvert.SerializeObject(nIBPDTOs);
        }


        [Router("/history/temp")]
        [WebApi(HttpMethodType.GET)]
        public string TempHistory(string deviceId)
        {
            Patient patient = WebContext.OnlinePatient[deviceId];
            if (patient == null)
            {
                return null;
            }
            PatientRepository patientRepository = new PatientRepository();
            MainDataTable dataTable = patientRepository.GetMainDataTables(patient.Id, 0);
            double[] Temp = CommonMethod.Instance.BytesToStruct<double>(dataTable.Temp).ToArray();
            var sampled = Temp.Where((value, index) => index % 60 == 0).ToArray();

            // 如果数据不满interval，全部显示

            List<TempDTO> tempDTOs = new List<TempDTO>();
            int i = 0;
            foreach (var temp in sampled)
            {
                TempDTO tempDTO = new TempDTO()
                {
                    t=CommonHelper.GetTimeStamp(dataTable.StartTime.AddMinutes(i)),
                    v = temp
                };
                i++;
                tempDTOs.Add(tempDTO);
            }

            return JsonConvert.SerializeObject(tempDTOs);
        }

    }
}
